﻿using System.IO;
using System.Text;
using UnityEngine;
namespace QQSDK
{
    public class KKFileUtils
    {
        private static string New_Line_character = "\n";
        private static DepData depData;
        public static void SetConfig(SDKData data)
        {
            LoadDepData();
            ConfigApplicationFile(data);
            SetManifestFile(data);
            SetGradleDependices(data);
        }
        public static void LoadDepData()
        {
            string configFilePath = Application.dataPath + "/QQSDK/Ads/Res/" + "dep.json"; //配置文件保存路径
            string json = File.ReadAllText(configFilePath);

            depData = JsonMapper.ToObject<DepData>(json);
        }
        /// <summary>
        /// 设置安卓依赖文件
        /// </summary>
        /// <param name="data"></param>
        static void SetGradleDependices(SDKData data)
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder mavenBuilder = new StringBuilder();
            //工具类
            sb.Append("implementation'com.kksdk:tools:latest.release'").Append(New_Line_character);
            //google play版本
            if (data.platformStore == 0)
            {
                mavenBuilder.Append("maven { url 'https://adcolony.bintray.com/AdColony'}") //adc
                    .Append(New_Line_character)
                    .Append(" maven { url 'https://s3.amazonaws.com/moat-sdk-builds'}") //mopub
                    .Append(New_Line_character)
                    .Append("maven { url 'https://dl.adtiming.com/android-sdk'}") //adt
                    .Append(New_Line_character)
                    .Append("maven { url 'https://dl.bintray.com/ironsource-mobile/android-sdk'}") //is
                    .Append(New_Line_character)
                    .Append("maven { url 'https://chartboostmobile.bintray.com/Chartboost'}") //charboost
                    .Append(New_Line_character)
                    .Append("maven { url 'https://fyber.bintray.com/marketplace'}") //fyber
                    .Append(New_Line_character)
                    .Append("maven { url 'https://dl.bintray.com/pubnative/maven'}") //pubnative
                    .Append(New_Line_character)
                    .Append("maven { url 'https://raw.githubusercontent.com/HyprMXMobile/Android-SDKs/master'}") //hyprmx
                    .Append(New_Line_character)
                    .Append("maven { url 'https://maven.ogury.co'}") //ogury
                    .Append(New_Line_character)
                    .Append("maven { url 'https://s3.amazonaws.com/smaato-sdk-releases/' }") //smaato
                    .Append(New_Line_character)
                    .Append("        maven {\n" +
                        "            name \"Tapjoy's maven repo\"\n" +
                        "            url \"https://tapjoy.bintray.com/maven\"\n" +
                        "        }"); //tapjoy
                sb.Append("implementation 'com.kksdk:unity_om_g:latest.release'");
            }
            //国内安卓版本
            else if (data.platformStore == 2)
            {
                sb.Append("implementation 'com.kksdk:unity_om_cn:latest.release'") //核心库
                    .Append(New_Line_character)
                    .Append("implementation 'com.kksdk:om_kkbid:latest.release'") //头条bid
                    .Append(New_Line_character)
                    .Append("implementation 'com.kksdk:om_tencent:latest.release'") //广点通
                    .Append(New_Line_character)
                    .Append("implementation 'com.kksdk:om_kuaishou:latest.release'") //快手
                    .Append(New_Line_character)
                    .Append("implementation 'com.kksdk:om_tiktok_cn:latest.release'") //头条
                    .Append(New_Line_character)
                    .Append("implementation 'com.kksdk:om_sigmob:latest.release'") //头条
                    .Append(New_Line_character);
                if (data.chinaStore.crashAnalyticsData.enable && !string.IsNullOrEmpty(data.chinaStore.crashAnalyticsData.bugly_app_id))
                {
                    sb.Append("implementation 'com.tencent.bugly:crashreport:latest.release'");
                }
            }
            string templateGradleText = File.ReadAllText(Application.dataPath + "/QQSDK/Ads/Res/kkmainTemplate.gradle");
            string dependicesText = templateGradleText.Replace("###$$###", sb.ToString());
            string allText = dependicesText.Replace(" ##REP##", mavenBuilder.ToString());
            string gradleText = File.ReadAllText(Application.dataPath + "/Plugins/Android/mainTemplate.gradle");
            gradleText.Replace(gradleText, "");
            File.WriteAllText(Application.dataPath + "/Plugins/Android/mainTemplate.gradle", allText);
        }
        /// <summary>
        /// 设置安卓清单文件
        /// </summary>
        /// <param name="data"></param>
        static void SetManifestFile(SDKData data)
        {
            StringBuilder sb = new StringBuilder();
            string appIDFormatString = "<meta-data android:name=\"{0}_app_id\" android:value=\"{1}\"/>";
            string bannerIDFormatString = "<meta-data android:name=\"{0}_banner_id\" android:value=\"{1}\"/>";

            string admobIDFormatsString = "<meta-data android:name=\"com.google.android.gms.ads.APPLICATION_ID\" android:value=\"{0}\"/>";
            string facebookIDFormatsString = "<meta-data android:name=\"com.facebook.sdk.ApplicationId\" android:value=\"{0}\"/>";

            string adjust_splash_im_token_formatString = "<meta-data android:name=\"sp_im\" android:value=\"{0}\"/>";
            string adjust_banner_im_token_formatString = "<meta-data android:name=\"ba_im\" android:value=\"{0}\"/>";
            string adjust_interstitial_im_token_formatString = "<meta-data android:name=\"in_im\" android:value=\"{0}\"/>";
            string adjust_reward_im_token_formatString = "<meta-data android:name=\"re_im\" android:value=\"{0}\"/>";

            string appID = string.Empty;
            string splashID = string.Empty;
            string bannerID = string.Empty;
            string interstitialID = string.Empty;
            string rewardVideoID = string.Empty;
            string applovinKey = string.Empty;
            string adjust_splash_token = string.Empty;
            string adjust_banner_token = string.Empty;
            string adjust_interstitial_token = string.Empty;
            string adjust_rewardVideo_token = string.Empty;

            appID = string.Format(appIDFormatString, "om", data.platformStore == 0 ? data.googleStore.openMediationData.app_id : data.chinaStore.openMediationData.app_id);
            bannerID = string.Format(bannerIDFormatString, "om", "om" + (data.platformStore == 0 ? data.googleStore.openMediationData.banner_id : data.chinaStore.openMediationData.banner_id));
            adjust_splash_token = string.Format(adjust_splash_im_token_formatString, data.platformStore == 0 ? data.googleStore.adjustData.splash_im_token : data.chinaStore.adjustData.splash_im_token);
            adjust_banner_token = string.Format(adjust_banner_im_token_formatString, data.platformStore == 0 ? data.googleStore.adjustData.banner_im_token : data.chinaStore.adjustData.banner_im_token);
            adjust_interstitial_token = string.Format(adjust_interstitial_im_token_formatString, data.platformStore == 0 ? data.googleStore.adjustData.interstitial_im_token : data.chinaStore.adjustData.interstitial_im_token);
            adjust_rewardVideo_token = string.Format(adjust_reward_im_token_formatString, data.platformStore == 0 ? data.googleStore.adjustData.rewardvideo_im_token : data.chinaStore.adjustData.rewardvideo_im_token);
            if (data.platformStore == 0)
            {
                sb
                    .Append(applovinKey)
                    .Append(New_Line_character)
                    .Append(string.Format(admobIDFormatsString, data.googleStore.admobData.app_id))
                    .Append(New_Line_character)
                    .Append(string.Format(facebookIDFormatsString, "fb" + data.googleStore.facebookData.app_id))
                    .Append(New_Line_character);
            }
            sb.Append(appID)
                .Append(New_Line_character)
                .Append(bannerID)
                .Append(New_Line_character)
                .Append(adjust_rewardVideo_token)
                .Append(New_Line_character)
                .Append(adjust_splash_token)
                .Append(New_Line_character)
                .Append(adjust_banner_token)
                .Append(New_Line_character)
                .Append(adjust_interstitial_token)
                .Append(New_Line_character);

            string templateAndroidManifest = File.ReadAllText(Application.dataPath + "/QQSDK/Ads/Res/tempAndoridMainfest");
            string productionAndroidManifest = File.ReadAllText(Application.dataPath + "/Plugins/Android/AndroidManifest.xml");
            productionAndroidManifest.Replace(productionAndroidManifest, "");
            string editorText = templateAndroidManifest.Replace("####&####", sb.ToString());
            File.WriteAllText(Application.dataPath + "/Plugins/Android/AndroidManifest.xml", editorText);
        }

        static void ConfigApplicationFile(SDKData data)
        {
            string Android_Application_Lanucher_File_Path = Application.dataPath + "/Plug-ins/Android/KKApplication.java";
            string firebaseString = "FirebaseApp.initializeApp(this);";
            string thinkingDataFormatString = "QQSDK.AnalyticsManager.instance().initThinkingData(this,\"{0}\");";
            string buglyInitFormatString = "Bugly.init(this,\"{0}\",false);";

            StringBuilder sb = new StringBuilder();

            if (data.platformStore == 0)
            {
                if (!data.googleStore.crashAnalyticsData.enable)
                {
                    firebaseString = string.Empty;
                }
                sb.Append(firebaseString)
                    .Append(New_Line_character)
                    .Append(string.Format(thinkingDataFormatString, data.googleStore.thinkingData.app_id))
                    .Append(New_Line_character)
                    .Append(getAdjustStirng(false, data.googleStore.adjustData));
            }
            else if (data.platformStore == 2)
            {
                sb.Append(string.Format(thinkingDataFormatString, data.chinaStore.thinkingData.app_id))
                    .Append(New_Line_character)
                    .Append(getAdjustStirng(true, data.chinaStore.adjustData))
                    .Append(New_Line_character);
                if (data.chinaStore.crashAnalyticsData.enable)
                {
                    sb.Append(string.Format(buglyInitFormatString, data.chinaStore.crashAnalyticsData.bugly_app_id));
                }
            }
            string applicationTemplateText = File.ReadAllText(Application.dataPath + "/QQSDK/Ads/Res/kkApplicationTemplate");
            string editorString = applicationTemplateText.Replace("###&&###", sb.ToString());
            string applicationText = File.ReadAllText(Android_Application_Lanucher_File_Path);
            applicationText.Replace(applicationText, "");
            File.WriteAllText(Android_Application_Lanucher_File_Path, editorString);
        }
        static string getAdjustStirng(bool chinaStore, SDKData.AdjustData adjustData)
        {
            string adjsutString = string.Empty;
            string adjustFormatStringWithSecret = "QQSDK.AnalyticsManager.instance.initAdjust(this,\"{0}\",{1},{2},{3},{4},{5},\"{6}\");";
            string adjustFormatStringWithSecretInChina = "QQSDK.AnalyticsManager.instance.initAdjustInChina(this,\"{0}\",{1},{2},{3},{4},{5},\"{6}\");";
            string adjustFormatString = "QQSDK.AnalyticsManager.instance.initAdjust(this,\"{0}\",\"{1}\");";
            string adjustFormatStringInChina = "QQSDK.AnalyticsManager.instance.initAdjust(this,\"{0}\",\"{1}\");";

            string default_track_name_string = string.Empty;
            string default_secrets_string = string.Empty;

            if (adjustData.enable_default_trackName && !string.IsNullOrEmpty(adjustData.default_trackName_token))
            {
                default_track_name_string = adjustData.default_trackName_token;
            }
            if (adjustData.enable_secrets)
            {
                if (!string.IsNullOrEmpty(adjustData.info1) &&
                    !string.IsNullOrEmpty(adjustData.info2) &&
                    !string.IsNullOrEmpty(adjustData.info3) &&
                    !string.IsNullOrEmpty(adjustData.info4) &&
                    !string.IsNullOrEmpty(adjustData.secretID))
                {
                    adjsutString = string.Format(chinaStore ? adjustFormatStringWithSecretInChina : adjustFormatStringWithSecret,
                        adjustData.app_token,
                        adjustData.secretID,
                        adjustData.info1,
                        adjustData.info2,
                        adjustData.info3,
                        adjustData.info4,
                        default_track_name_string);
                }
                else
                {
                    adjsutString = string.Format(chinaStore ? adjustFormatStringInChina : adjustFormatString, adjustData.app_token, default_track_name_string);
                }
            }
            else
            {
                adjsutString = string.Format(chinaStore ? adjustFormatStringInChina : adjustFormatString, adjustData.app_token, default_track_name_string);
            }
            return adjsutString;
        }
    }
}